package com.aliang.book_java1.service.Impl;

import com.aliang.book_java1.service.LogicalManage;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.*;

@Service
public class LogicalManageImpl implements LogicalManage {
    @Override
    public JSONArray uploadExcel(String type, MultipartFile file) throws Exception{
        JSONArray jsonArray=new JSONArray();
        Sheet sheet;
        if(type.endsWith(".xls")){
            Workbook workbook= new HSSFWorkbook(file.getInputStream());
            sheet = workbook.getSheetAt(0);    //获得第一个表单sheet
        }else {
            XSSFWorkbook workbook= new XSSFWorkbook(file.getInputStream());
            sheet = workbook.getSheetAt(0);    //获得第一个表单sheet
        }
        int rowCount = sheet.getLastRowNum()+1;//总行数
        Row firstRow=sheet.getRow(0);//获取标题行
        int columnCount=firstRow.getLastCellNum();//总列数
        Map<Integer,String> titleMap=getTitleMap(firstRow,columnCount,0);
        /*for(int i = 1; i < rowCount;i++){  //第一行是标题

        }*/
        //递归调用，获每一行数据（从第二行开始，第一行是标题）
        getRowValue(sheet,columnCount,rowCount,1,titleMap,jsonArray);
        return  jsonArray;
    }

    @Override
    public Map<String, Object> getComputerInfo() throws Exception{
        Map<String,Object> infoMap=new HashMap<>();
        // CPU信息
        Properties props = System.getProperties();
        String cpuInfo = "CPU信息: " + props.getProperty("os.name") + " " + props.getProperty("os.version") + " " + props.getProperty("os.arch");
        infoMap.put("CPU:",cpuInfo);

        // 内存信息
        Runtime runtime = Runtime.getRuntime();
        long totalMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();
        long usedMemory = totalMemory - freeMemory;
        String memoryInfo = "内存信息: 总内存=" + totalMemory / 1024 / 1024 + "MB, 已用内存=" + usedMemory / 1024 / 1024 + "MB, 剩余内存=" + freeMemory / 1024 / 1024 + "MB";
        infoMap.put("内存:",memoryInfo);

        // 磁盘信息
        // 磁盘信息通常需要操作系统级别的命令或者第三方库来获取

        // 网络信息
        InetAddress ip = InetAddress.getLocalHost();
        String networkInfo = "网络信息: IP地址=" + ip.getHostAddress();
        infoMap.put("IP:",networkInfo);

        // 网络接口信息
        NetworkInterface networkInterface = NetworkInterface.getByInetAddress(ip);
        if (networkInterface != null) {
            try {
                byte[] mac = networkInterface.getHardwareAddress();
                StringBuffer sb = new StringBuffer("");
                for (int i = 0; i < mac.length; i++) {
                    sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                }
                String macAddress = "MAC地址: " + sb.toString();
                infoMap.put("MAC:",macAddress);
            }catch (Exception e){

            }

        }
        return infoMap;
    }

    @Override
    public Map<String, Integer> countWordFrequency(String news) throws Exception {
        // 假设的分词函数，这里简单使用空格分割
        String[] words = news.split("\\s+"); // 使用正则表达式分割单词，包括空格、换行等

        // 用于存储词频的Map
        Map<String, Integer> frequencyMap = new HashMap<>();

        // 遍历分词结果，统计词频
        for (String word : words) {
            // 更新词频
            frequencyMap.put(word, frequencyMap.getOrDefault(word, 0) + 1);
        }

        return frequencyMap;
    }

    /**
     *
     * @param row 标题行
     * @param columnCount 列数
     * @param rowIndex 行标
     * @return
     */
    private Map<Integer,String> getTitleMap(Row row,Integer columnCount,Integer rowIndex){
        Map<Integer,String> titleMap=new HashMap<>();
        if(row!=null){
            for(int j=0;j<columnCount;j++) {
                String lineContent = "";
                try {
                    lineContent = getCellValue(row.getCell(j));
                } catch (Exception e) {
                    //此处可输出日志，为了节省做面试题效率，故采用系统输出
                    System.out.println("error:第"+(rowIndex+1)+"行，第"+(j+1)+"列数据解析失败");
                }
                titleMap.put(j,lineContent);
            }
        }
        return titleMap;
    }

    /**
     *
     * @param sheet  数据表
     * @param columnCount  列数
     * @param rowCount   行数
     * @param rowIndex   当前行
     * @param titleMap   标题字典
     * @param jsonArray  数据集合
     */
    private void getRowValue(Sheet sheet, Integer columnCount,Integer rowCount,
                                   Integer rowIndex, Map<Integer,String> titleMap,
                                   JSONArray jsonArray){
        if(rowIndex<rowCount){
            JSONObject jsonObject=new JSONObject();
            Row row = sheet.getRow(rowIndex);
            if(row!=null){
                for(int j=0;j<columnCount;j++) {
                    String lineContent = "";
                    try {
                        lineContent = getCellValue(row.getCell(j));
                        //System.out.println("----lineContent---"+ JSON.toJSONString(lineContent));
                    } catch (Exception e) {
                        //此处可输出日志，为了节省做面试题效率，故采用系统输出
                        System.out.println("error:第"+(rowIndex+1)+"行，第"+(j+1)+"列数据解析失败");
                    }
                    //rowVal.add(lineContent);
                    if(titleMap.containsKey(j)){//根据列名匹配字段名（中文标题可以做响应转义）
                        jsonObject.put(titleMap.get(j),lineContent);
                    }
                }
            }
            jsonArray.add(jsonObject);
            //return jsonObject;
            rowIndex++;
            getRowValue(sheet,columnCount,rowCount,rowIndex,titleMap,jsonArray);
        }

    }

    /**
     * 获取单元格的值
     * @param cell
     * @return
     */
    public String getCellValue(Cell cell) throws Exception{
        //正常情况下这里可以根据数据类型不同做不同的处理
        return cell.getStringCellValue();

    }
}
